package leetcode_bin_tree_test;

import bin_tree.TreeNode;

/**
 * 剑指 Offer II 056. 二叉搜索树中两个节点之和
 */
public class FindTargetSearch {
    static TreeNode treeRoot;
//    static boolean ret;
    public static boolean findTarget(TreeNode root, int k) {
        // 使用中序遍历，从小到大看是否能找到另一半和
        if (root == null) {
            return false;
        }
        treeRoot = root;
        return findTarget1(root, k);
//        return ret;
    }

    public static boolean findTarget1(TreeNode root, int k) {
        if (root == null) {
            return false;
        }
        if(findTarget1(root.left, k)) {
//            ret = true;
            return true;
        }
        int sub = k - root.val;
        return sub != root.val && (find(treeRoot, sub) || findTarget1(root.right, k));
    }

    public static boolean find(TreeNode root, int sub) {
        if (root == null) {
            return false;
        }
        if (root.val == sub) {
            return true;
        }
        return sub < root.val ? find(root.left, sub) : find(root.right, sub);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(8);
        TreeNode node1 = new TreeNode(6);
        TreeNode node2 = new TreeNode(10);
        TreeNode node3 = new TreeNode(5);
        TreeNode node4 = new TreeNode(7);
        TreeNode node5 = new TreeNode(9);
        TreeNode node6 = new TreeNode(11);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        node2.right = node6;
        System.out.println(findTarget(root, 22));
    }
}
